package com.ruoyi.controller;



import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.network.DeviceOnline;
import com.ruoyi.network.MessageBus;
import com.ruoyi.network.OnlineDeviceManager;
import com.ruoyi.network.message.SendMessageGenerator;
import com.ruoyi.ufox.domain.BisDevice;
import com.ruoyi.ufox.service.impl.BisDeviceServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;

@RestController
@RequestMapping("/device")
public class DeviceController {

    @Autowired
    private OnlineDeviceManager onlineDeviceManager;

    @Autowired
    private MessageBus messageBus;
    @Autowired
    private BisDeviceServiceImpl deviceService;
    //@Autowired
    //private BisDevice bisDevice;

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");




    @GetMapping("/online-count")
    public Integer getOnlineCount(){

        for (String deviceCode : onlineDeviceManager.getAllOnlineDevices().keySet()) {

            DeviceOnline deviceOnline = onlineDeviceManager.getAllOnlineDevices().get(deviceCode);
            System.out.println(deviceCode+""+dateFormat.format(deviceOnline.getJoinTime())+"\t"+dateFormat.format(deviceOnline.getLastHeartBeat()));
        }

        return onlineDeviceManager.getAllOnlineDevices().size();
    }

    @GetMapping("/open-light")
    public String openLight(String deviceCode){

        String s = SendMessageGenerator.generateOpenLightCommand(100).toHexString();
        messageBus.asyncSendMessage(s, deviceCode);

       // bisDevice.setLighterStatus(1L);
      //  deviceService.updateBisDevice(deviceCode)


       return "ok";
        // return new AjaxResult(200,"成功");
    }

    @GetMapping("/open-fan")
    public String openFan(String deviceCode){
        String hex = SendMessageGenerator.generateSwithFan(true).toHexString();
        messageBus.asyncSendMessage(hex, deviceCode);

        return "ok";
    }

    @GetMapping("/close-fan")
    public String closeFan(String deviceCode) {

        String hex = SendMessageGenerator.generateSwithFan(false).toHexString();
        messageBus.asyncSendMessage(hex, deviceCode);
        return "ok";
    }
    @GetMapping("/open-beng")
    public String openbeng(String deviceCode){
        String hex = SendMessageGenerator.generateSwithPump(true).toHexString();
        messageBus.asyncSendMessage(hex, deviceCode);

        return "ok";
    }

}
